// pages/index/details/index.js
const $api = require('../../../../request/api').API;
import Dialog from '../../../../miniprogram_npm/@vant/weapp/dialog/dialog';
import Toast from '../../../../miniprogram_npm/@vant/weapp/toast/toast';
const app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    // 呼叫器id
    beeperId: '',
    // 设备id
    equipId: '',
    equipMac: '',
    //--------------------------------------------------------------
    phone: '',
    linkName: '',
    address: '',
    houseNumber: '',
    provinceName: '',
    cityName: '',
    areaName: '',
    streetName: '',
    villageName: '',
    callingName: '',
    equipNickName: '',
    phoneTwo: '',
    installArea: '',
    equipCode: '',
    flowEndDate: '',
    callingStatus: 0,
    money: 0,
    wxAppUrl: '',
    // 标签列表
    tagList: [
      {
        beeperTagId: '1',
        tagName: '帅气'
      }
    ],
    // 颜色列表
    tagColor: [
      '#7FFFAA',
      '#ff7070',
      '#EEC900',
      '#4876FF',
      '#ff6100',
      '#FFA500',
      '#7DC67D',
      '#E17572',
      '#7898AA',
      '#C35CFF',
      '#33BCBA',
      '#C28F5C',
      '#FF8533',
      '#6E6E6E',
      '#428BCA',
      '#5cb85c',
      '#FF674F',
      '#E9967A',
      '#66CDAA',
      '#00CED1',
      '#9F79EE',
      '#CD3333',
      '#FFC125',
      '#32CD32',
      '#00BFFF',
      '#68A2D5',
      '#FF69B4',
      '#DB7093',
      '#CD3278',
      '#607B8B'
    ],
    // 新增标签名
    addTagName: '',
    //-----------------------------------------------------------------
    // 设置wifi弹框
    // showWifiOverlay:false,
    // 设置新增标签弹框
    showTagOverlay: false,
    // 点击标签分类显示
    selectClassShow: false,
    selectClassName: '点击选择分类',
    selectClassId: '',
    tagClass: [],
    // 设置标签为可删除
    tagClose: false,
    // 服务列表
    serviceList: [],
    // 是否为主用户
    mainFlag: 0,
    // 修改昵称或者安装区域弹框
    showUpdateData: false,
    showType: 1, //1代表昵称修改 2代表安装区域修改
    tempData: '', //临时数据，用来修改昵称和安装区域
    // 经纬度
    latitude: '',
    longitude: '',
    voiceShow: false,
    voiceTitle: 1,
    // 类型
    beeperType: '',
    beeperVersion: '',
    powerLevel: '',
    showBeeperQrcode: false,
    defaultOpen: '',
    content: 1
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let id = options.beeperId;
    if (id != undefined) {
      this.setData({
        beeperId: options.beeperId
      });
    }
  },

  // 请求数据
  getData(id) {
    let params = {
      id: id
    };
    $api
      .getBeeper(params)
      .then(res => {
        if (res.data.status === 0) {
          var data = res.data.data;
          this.setData({
            beeperId: data.beeperId,
            equipId: data.equipId,
            phone: data.phone,
            linkName: data.linkName,
            address: data.address === '待补充' ? '' : data.address,
            houseNumber: data.houseNumber,
            provinceName: data.provinceName,
            equipNickName: data.equipNickName,
            installArea: data.installArea,
            equipCode: data.equipCode,
            flowEndDate: data.flowEndDate == null ? '' : data.flowEndDate,
            cityName: data.cityName,
            areaName: data.areaName,
            streetName: data.streetName,
            villageName: data.villageName,
            callingName: data.equipName,
            callingStatus: data.equipState,
            phoneTwo: data.phoneTwo,
            money: data.balance,
            tagList: data.tags,
            mainFlag: data.mainFlag,
            latitude: data.latitude,
            longitude: data.longitude,
            beeperType: data.beeperType,
            beeperVersion: data.beeperVersion,
            powerLevel: data.powerLevel,
            wxAppUrl: data.wxAppUrl,
            defaultOpen: data.defaultOpen,
            equipMac: data.equipMac
          });
          app.globalData.serviceList = data.beeperBtnList;
          this.getTagData();
        }
      })
      .catch(err => {
        console.log(err);
      });
  },

  // 获取标签分类数据
  getAllService() {
    $api
      .getTagService({
        beeperId: this.data.beeperId
      })
      .then(res => {
        this.setData({
          tagClass: res.data.data
        });
      });
  },

  // 显示所有标签后面的关闭
  showTagClose() {
    this.setData({
      tagClose: !this.data.tagClose
    });
  },
  // 打开新增tag弹框
  openTagOverlay() {
    this.setData({
      showTagOverlay: true
    });
    this.getAllService();
  },
  // 关闭新增tag弹框
  closeTagOverlay() {
    this.setData({
      showTagOverlay: false
    });
  },
  // 打开修改弹框
  openUpdateData(e) {
    let type = e.currentTarget.dataset.type;
    if (!this.data.mainFlag && type == 1) return;
    this.setData({
      showUpdateData: true,
      showType: type,
      tempData: type == 1 ? this.data.equipNickName : type == 2 ? this.data.installArea : this.data.phoneTwo
    });
  },

  // 关闭修改昵称弹框
  closeUpdateData() {
    this.setData({
      showUpdateData: false
    });
  },
  // 输入绑定
  dataInput(e) {
    let value = e.detail.value;
    this.setData({
      tempData: value
    });
  },
  // 修改昵称
  UpdateData() {
    if (!this.data.tempData && this.data.showType === 1) {
      Toast('请输入昵称');
      return;
    } else if (!this.data.tempData && this.data.showType === 2) {
      Toast('请输入安装区域');
      return;
    } else if (!this.data.tempData && this.data.showType === 3) {
      Toast('请输入备用电话');
      return;
    }
    if (this.data.showType === 3) {
      $api
        .setPhoneTwo({
          beeperId: this.data.beeperId,
          phoneTwo: this.data.tempData
        })
        .then(res => {
          if (res.data.status === 0) {
            wx.showToast({
              title: '设置成功'
            });
            this.setData({
              showUpdateData: false,
              tempData: ''
            });
            this.getData(this.data.beeperId);
          }
        })
        .catch(err => {
          console.log(err);
        });
    } else {
      let params = {
        id: this.data.equipId,
        name: this.data.tempData,
        state: this.data.showType
      };
      $api
        .UpdataName(params)
        .then(res => {
          if (res.data.status === 0) {
            if (this.data.showType === 1) {
              wx.showToast({
                title: '设置昵称成功'
              });
            } else {
              wx.showToast({
                title: '设置安装区域成功'
              });
            }
            this.setData({
              showUpdateData: false
            });
            this.getData(this.data.beeperId);
          }
        })
        .catch(err => {
          console.log(err);
        });
    }
  },
  // 修改设置
  modifyDefaultOpen() {
    let { defaultOpen, mainFlag } = this.data;
    if (!mainFlag) return;
    let params = {
      id: this.data.beeperId,
      state: defaultOpen === 1 ? 2 : 1
    };
    let message = defaultOpen === 1 ? '确认修改为全部?' : '确认修改为精选';
    Dialog.confirm({
      title: '提示',
      message: message
    }).then(() => {
      $api.setDefalutOpen(params).then(res => {
        if (defaultOpen === 1) {
          this.setData({
            defaultOpen: 2
          });
          Toast.success('设置全部成功');
        } else if (defaultOpen === 2) {
          this.setData({
            defaultOpen: 1
          });
          Toast.success('设置精选成功');
        }
      });
    });
  },
  // 打开tag分类弹框
  openSelectClass() {
    this.setData({
      selectClassShow: true
    });
  },
  // 关闭tag分类弹框
  closeSelectClass() {
    this.setData({
      selectClassShow: false
    });
  },
  onSelectClass(event) {
    this.setData({
      selectClassName: event.detail.name,
      selectClassId: event.detail.id
    });
  },
  // 新增标签
  addTag() {
    let name = this.data.addTagName;
    let id = this.data.beeperId;
    let classId = this.data.selectClassId;

    if (classId == '') {
      Toast.fail('请选择分类');
      return;
    }
    if (name == '') {
      Toast.fail('请填写名称');
      return;
    }
    let params = {
      beeperId: id,
      tagName: name,
      classifyId: classId
    };
    $api
      .tagAdd(params)
      .then(res => {
        if (res.data.status === 0) {
          wx.showToast({
            title: '新增标签成功'
          });
          this.setData({
            showTagOverlay: false
          });
          this.getData(this.data.beeperId);
        }
      })
      .catch(err => {
        console.log(err);
      });
  },

  // 删除标签
  onCloseTag(e) {
    let deleteId = e.currentTarget.dataset.id;
    var { tagList } = this.data;
    let params = {
      id: deleteId,
      state: -1
    };
    $api
      .tagDelete(params)
      .then(res => {
        if (res.data.status == 0) {
          // 使用数组的findIndex方法 找到与需删除的id的 元素下标，再用splice删除。
          tagList.splice(
            tagList.findIndex(item => item.id == deleteId),
            1
          );
          wx.showToast({
            title: '标签删除成功'
          });
          this.setData({
            tagList
          });
          this.getData(this.data.beeperId);
        }
      })
      .catch(err => {
        console.log(err);
      });
  },

  // 跳转充值页
  goTopUp() {
    wx.navigateTo({
      url: '../topUp/index?id=' + this.data.beeperId
    });
  },
  // 跳转服务列表
  toServiceList() {
    wx.navigateTo({
      url: '../serviceList/index?id=' + this.data.beeperId
    });
  },
  // 跳转用户列表
  toUserList() {
    wx.navigateTo({
      url: '../userList/index?id=' + this.data.beeperId
    });
  },
  toOrder() {
    app.globalData.beeperOrderId = this.data.beeperId;
    wx.switchTab({
      url: '/pages/order/index'
    });
  },
  // 去呼叫器地址页面
  toBeeperAddress() {
    wx.navigateTo({
      url: '/subcontract/person/pages/beeperAddress/index?id=' + this.data.beeperId
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.getData(this.data.beeperId);
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {},
  tagNameInput(e) {
    let value = e.detail.value;
    this.setData({
      addTagName: value
    });
  }
});
